/*
 * Google Calendar Content Script Manager
 * This content just handle the dom object are in Calendar page scope 
 */
var settings = null;
var selectedCalendar = 'ALL';

function trim(string)
{
    return string.replace(/^\s+|\s+$/g, '');
};

function selectCalendar()
{    
    var target = $('.cb-calendar');
    if((!target) || (!target.attr('id')))
        return;        
    var inputId = target.attr('id');    
    if (inputId==='')
        return;
    var options = document.getElementById(inputId);
    if (!options)
        return;        
    for (var i = 0; i < options.children.length; i++) {
        var child = options.children[i];
        if (child.value == selectedCalendar) {
            child.selected = "true";
            break;
        }
    }    
}

/**
 * Get focus on appointment
**/
function onInputFocus(e) 
{
    // INPUT BOX of Calendar: INPUT ID = #:n.what  the number n is always changing. - class: textbox-fill-input
    // INPUT BOX of Calendar: SELECT ID = #:n.calendar  - the number n is always changing - class: cb-calendar
    var target = $(this);
    if((!target) || (!target.attr('id')))
        return true;        
    var inputId = target.attr('id');    
    if (inputId==='')
        return true;
		
	/**
	 * OnCreate Button Clicked.
	**/
	$('td.cb-actions>span>div').mousedown(function(e){
		var dropbox = $('.cb-calendar');
		if((!dropbox) || (!dropbox.attr('id')))
			return true;
		
		var request = {
			action: "onCreateClicked",
			calendarId: dropbox.val(),
			calendarTitle: null,
			eventTitle: target.val()
		};
		
		// Check all calendars
		if (dropbox[0].length>0){
			for(var i=0;i<dropbox[0].length;i++){
			   if (dropbox[0][i].selected && dropbox[0][i].value==selectedCalendar){
				  request.calendarTitle=dropbox[0][i].text;
				  break;
			   }
			}
		}
		
		selectedCalendar =  request.calendarId; // Store it on memory
		chrome.extension.sendRequest(request, function(response) {
			/**
			 * Send to Glinic
			**/
			//target.val(selectedCalendar);
		});
		return true;
	});
	
    var as_json = new AutoSuggest(inputId,{
		script:null,
		varname:"input",
		json:true,
		callback: function (obj, typedstr) { 
			if (!settings)
				return;
			var val = obj.value;           
			var sep=(settings.eventduration!=60)?'_':' ';
			var text = '';
			var words = trim(obj.value).split(' ');
			if (words.length==1){
				text = words[0];
			}
			else if (words.length==2){
				text = words[0]+sep+words[1];
			}
			else if (words.length>2){
				var unionchr = '';
				var tmp = '';
				var wcount = 0;
				for(var i=0;i<words.length;i++){
					tmp = tmp + unionchr + words[i];
					unionchr = sep;
					wcount = wcount+1;
					if (wcount>=settings.nwords)
						break;
				}
				if (tmp!=='')
					text = tmp;                    
			}
			if (text!==''){
				if (settings.eventduration!=60)
					text=text+' for ' + settings.eventduration + ' minutes';
				text = trim(text);
				var pos = typedstr.search('[a-z|A-Z]');            
				if (pos>0)
					text = typedstr.substr(0,pos) + text;                
				target.val(text);
			}
		}
	});
    selectCalendar();    
    e.stopPropagation();
};

// background page function handler:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
    if(request.action == 'enable'){
        selectedCalendar = request.calendarId;
        $('.textbox-fill-input').live('focus', onInputFocus);
		//htm=$('div.bubble-top').html();
		//$('div.bubble-top').html('<a href="#">faltou</a> | <a href="#">report</a>' );
        //$('td.cb-actions>span>div').live('mouseup',onCreateClicked);  
		//$('table.eb-data>tbody>tr>td')
		//$('td.bubble-mid>div').bind('change visibility',function() {
		//	console.log('mudou');
		//});

        sendResponse(true);
    }
    else if(request.action == 'disable'){
        $('.textbox-fill-input').die('focus', onInputFocus);
        //$('td.cb-actions>span>div').die('mouseup',onCreateClicked);
        sendResponse(true);
    }
    else if(request.action == 'updateSettings'){
        settings = request.data;
        var email = $('#guser > b');
        if (email){
            settings.domain = trim(email.text());
        }
        else{
            console.log('email error');
        }
        sendResponse(settings);
    }
    else{
        sendResponse(false);
    }
});

